package com.manager.user.utils;

import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 多文件下载工具类
 */
public class MultiFileDownloadUtil {

    /**
     * 将多个文件打包成ZIP并写入输出流
     * @param filePaths 要打包的文件路径列表
     * @param outputStream 输出流
     * @throws IOException 异常
     */
    public static void zipFiles(List<String> filePaths, OutputStream outputStream) throws IOException {
        if (filePaths == null || filePaths.isEmpty()) {
            throw new IllegalArgumentException("文件列表不能为空");
        }

        try (ZipOutputStream zos = new ZipOutputStream(outputStream)) {
            byte[] buffer = new byte[4096];

            for (String filePath : filePaths) {
                File file = new File(filePath);
                addFileToZip(zos, buffer, file);
            }
        }
    }

    /**
     * 将单个文件添加到ZIP输出流
     */
    private static void addFileToZip(ZipOutputStream zos, byte[] buffer, File file) throws IOException {
        if (!file.exists() || !file.isFile()) {
            return;
        }

        try (FileInputStream fis = new FileInputStream(file)) {
            ZipEntry zipEntry = new ZipEntry(file.getName());
            zos.putNextEntry(zipEntry);

            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                zos.write(buffer, 0, bytesRead);
            }

            zos.closeEntry();
        }
    }

    /**
     * 创建临时ZIP文件
     */
    public static File createTempZipFile(List<String> filePaths) throws IOException {
        File tempZip = File.createTempFile("temp_", ".zip");
        tempZip.deleteOnExit(); // JVM退出时删除临时文件

        try (FileOutputStream fos = new FileOutputStream(tempZip)) {
            zipFiles(filePaths, fos);
        }

        return tempZip;
    }
}
